package com.hmj.hmjaiagent.demo.invoke;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;

/**
 * Http方式调用
 */
public class HttpAiInvoke {
    private static final String API_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
    private static final String API_KEY = TestApiKey.API_KEY; // 替换为你的实际API Key

    public static void main(String[] args) {
        // 构建请求体JSON
        JSONObject requestBody = new JSONObject();
        requestBody.set("model", "qwen-turbo");

        // 构建input部分
        JSONObject input = new JSONObject();
        JSONArray messages = new JSONArray();

        // 添加系统消息
        JSONObject systemMessage = new JSONObject();
        systemMessage.set("role", "system");
        systemMessage.set("content", "You are a helpful assistant.");
        messages.add(systemMessage);

        // 添加用户消息
        JSONObject userMessage = new JSONObject();
        userMessage.set("role", "user");
        userMessage.set("content", "你是谁？");
        messages.add(userMessage);

        input.set("messages", messages);
        requestBody.set("input", input);

        // 添加parameters部分
        JSONObject parameters = new JSONObject();
        parameters.set("result_format", "message");
        requestBody.set("parameters", parameters);

        // 发送HTTP请求
        HttpResponse response = HttpRequest.post(API_URL)
                .header("Authorization", "Bearer " + API_KEY)
                .header("Content-Type", "application/json")
                .body(requestBody.toString())
                .execute();

        // 处理响应
        if (response.isOk()) {
            String responseBody = response.body();
            System.out.println("API响应: " + responseBody);

            // 解析JSON响应
            JSONObject jsonResponse = JSONUtil.parseObj(responseBody);
            // 这里可以根据需要处理响应数据
        } else {
            System.out.println("请求失败，状态码: " + response.getStatus());
            System.out.println("错误信息: " + response.body());
        }
    }
}
